import { _decorator, Component, instantiate, math, Node, Prefab } from "cc";
import { Pipe } from "./Pipe";
const { ccclass, property } = _decorator;

@ccclass("PipeSpawn")
export class PipeSpawn extends Component {
  @property(Prefab)
  public pipePrefab: Prefab = null;

  @property
  public spawnRate = 1.5;

  private _canSpawing: boolean = true;

  public spawnPipeTimer = 0;

  protected onLoad() {}
  protected start() {}

  protected update(deltaTime: number) {
    if (!this._canSpawing) return;
    this.spawnPipeTimer += deltaTime;
    if (this.spawnPipeTimer >= this.spawnRate) {
      this.spawnPipeTimer = 0;
      this.spawnPipe();
    }
  }

  public spawnPipe(): void {
    const newPipe = instantiate(this.pipePrefab);
    this.node.addChild(newPipe);
    const parent = this.node.getWorldPosition();
    const randomY = math.randomRange(-100, 200);
    newPipe.setWorldPosition(parent.x, parent.y + randomY, parent.z);
  }

  public enablePipeSpawn() {
    this._canSpawing = true;
  }

  public disablePipeSpawn() {
    this._canSpawing = false;
    this.node.children.forEach((child) => {
      child.getComponent(Pipe).enabled = false;
    });
  }
}
